package registry

import "kubeInstall/model/registry/http"

type Repository struct {
	Name          string `json:"name"`
	ID            int64  `json:"id"`
	ProjectID     int64  `json:"project_id"`
	UpdateTime    string `json:"update_time"`
	CreationTime  string `json:"creation_time"`
	ArtifactCount int64  `json:"artifact_count"`
	Description   string `json:"description"`
}

type ListRepositoryOpts struct {
	Page     int `q:"page"`
	PageSize int `q:"page_size"`
}

type ListRepositoryBuilder interface {
	ToListQuery() (string, error)
}

func (opts ListRepositoryOpts) ToListQuery() (string, error) {
	q, err := http.BuildQueryString(opts)
	return q.String(), err
}

type CreateRepositoryOpts struct {
	Description string `json:"description"`
}

func ListRepository(projectName string, opts ListRepositoryBuilder) ([]Repository, error) {

	var p []Repository
	url := "/api/v2.0/projects/" + projectName + "/repositories"
	if opts != nil {
		query, err := opts.ToListQuery()
		if err != nil {
			return nil, err
		}
		url += query
	}

	resp, err := registryClient.Get(url)

	if err != nil {
		return nil, err
	}

	err = http.ExtractInto(resp.Body, &p)

	if err != nil {
		return nil, err
	}
	return p, nil
}

func GetRepository(projectName, repositoryName string) (Repository, error) {
	var p Repository
	url := "/api/v2.0/projects/" + projectName + "/repositories/" + repositoryName

	resp, err := registryClient.Get(url)

	if err != nil {
		return p, err
	}

	err = http.ExtractInto(resp.Body, &p)

	if err != nil {
		return p, err
	}
	return p, nil

}

func UpdateRepository(projectName, repositoryName string, opts CreateRepositoryOpts) error {

	url := "/api/v2.0/projects/" + projectName + "/repositories/" + repositoryName

	_, err := registryClient.PUT(url, opts)

	return err

}

func DeleteRepository(projectName, repositoryName string) error {

	url := "/api/v2.0/projects/" + projectName + "/repositories/" + repositoryName

	_, err := registryClient.Delete(url)

	return err

}
